package com.authine.cloudpivot.ext.applicationservice;

import cn.hutool.core.date.DateUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.CustomerStatistics.CustomerStatisticInfoDto;
import com.authine.cloudpivot.ext.dto.CustomerStatistics.CustomerStatisticResultDto;
import com.authine.cloudpivot.ext.dto.CustomerStatistics.CustomerStatisticsDto;
import com.authine.cloudpivot.ext.dto.OrgInfoDto;
import com.authine.cloudpivot.ext.dto.PageObject;
import com.authine.cloudpivot.ext.dto.SaleStatisticsDto;
import com.authine.cloudpivot.ext.dto.system.OrganizationDto;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.enums.CustomerStatisticEnum;
import com.authine.cloudpivot.ext.enums.FileExportEnum;
import com.authine.cloudpivot.ext.enums.report.ReportType;
import com.authine.cloudpivot.ext.model.ReportRecord;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.cloudpivot.ext.utils.system.BeanUtils;
import com.authine.cloudpivot.ext.utils.system.ReportUtils;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static com.authine.cloudpivot.ext.conf.ApplicationConf.EXPORT_REPORT_URL;
import static com.authine.cloudpivot.ext.conf.ApplicationConf.systemManagement;
import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Slf4j
@Path("CustomerStatisticsService")
public class CustomerStatisticsService extends ApplicationService {


    @Path("queryCustomerStatistics")
    @POST
    @Operation(summary = "新版客户数据统计",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> queryCustomerStatistics(@Parameter CustomerStatisticsDto good){
        //查询客户组织名称
        List<Map<String,Object>> params = new ArrayList<>();
        PageObject<Map<String, Object>> pageObject = new PageObject<Map<String, Object>>();

        List<CustomerStatisticInfoDto> customers = new ArrayList<>();
        Integer count = 0;
        try {
            Integer pageCurrent = good.getPageCurrent() == null ? 1 : good.getPageCurrent();
            Integer pageSize = good.getPageSize() == null ? 10 : good.getPageSize();
            // 设置当前页
            good.setPageCurrent(pageCurrent);
            // 设置每页显示的条数
            pageObject.setPageSize(pageSize);
            // 设置总记录数

            count = CustomerStatisticsJdbcUtil.queryAllCustomerCount(good);
            log.info("总条数:{}" + count);
            pageObject.setRowCount(count);
            pageObject.setPageCount(0);
            if (count != 0) {
                // 设置总页数
                int pageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                pageObject.setPageCount(pageNum);
                // 设置每页显示数据集合
                // 开始的记录数
                int start = (pageCurrent - 1) * pageSize;
                System.out.println(start + "-" + pageSize);
                customers = CustomerStatisticsJdbcUtil.queryAllCustomers(good, start, pageSize);
                StringBuffer sbNames = new StringBuffer();
                if (customers != null && customers.size() > 0){
                    customers.forEach(item->{
                        String name = (String) item.getName();
                        if (StringUtils.isNotBlank(name)){
                            sbNames.append(name);
                            sbNames.append(",");
                        }
                    });
                }
                sbNames.deleteCharAt(sbNames.length() - 1);
                //查询询价商品条数
                List<CustomerStatisticResultDto> inquiryGoods = CustomerStatisticsJdbcUtil.queryInquiryGoodNum(good, sbNames);
                packageCustomerStatistics(inquiryGoods,customers,CustomerStatisticEnum.inquiry_good_num.getId());


                //澄清询价商品条数
                List<CustomerStatisticResultDto> inquirGoodClarifys = CustomerStatisticsJdbcUtil.quiryInqueryGoodClarifyCount(good,sbNames);
                packageCustomerStatistics(inquirGoodClarifys,customers,CustomerStatisticEnum.clarify_record_count.getId());

                //未报价询价商品条数
                List<CustomerStatisticResultDto> unQuotationGoods = CustomerStatisticsJdbcUtil.quiryQuotationQuoteCount(good, sbNames);
                packageCustomerStatistics(unQuotationGoods,customers,CustomerStatisticEnum.quote_count_num.getId());

                //原供应商参与询价商品条数 暂无



//                List<CustomerStatisticResultDto> oldVendorInquiryGoods = CustomerStatisticsJdbcUtil.queryOldVendorInquiryGoodCount(good, sbNames);
//                packageCustomerStatistics(oldVendorInquiryGoods,customers,CustomerStatisticEnum.invite_code_num.getId());

                //客户订单商品条数

                List<CustomerStatisticResultDto> customerOrderGoods = CustomerStatisticsJdbcUtil.queryCustomerOrderGoodNum(good, sbNames);
                packageCustomerStatistics(customerOrderGoods,customers,CustomerStatisticEnum.order_goods.getId());


                //原供应商订单商品条数
                List<CustomerStatisticResultDto> oldVendorGoods = CustomerStatisticsJdbcUtil.queryOldVendorOrderGoodNum(good,sbNames,1);
                packageCustomerStatistics(oldVendorGoods,customers,CustomerStatisticEnum.platform_num.getId());


                //平台供应商订单商品条数
                List<CustomerStatisticResultDto> plateVendorGoods = CustomerStatisticsJdbcUtil.queryOldVendorOrderGoodNum(good,sbNames,0);
                packageCustomerStatistics(plateVendorGoods,customers,CustomerStatisticEnum.old_platformNum.getId());

                //订单金额
                List<CustomerStatisticResultDto> customerOrderTotal  = CustomerStatisticsJdbcUtil.queryCustomerOrderTotal(good,sbNames);
                packageCustomerStatistics(customerOrderTotal,customers,CustomerStatisticEnum.orderMoney.getId());

                //原供应商订单金额
                List<CustomerStatisticResultDto> customerStatisticResultDtos1 = CustomerStatisticsJdbcUtil.queryVendorOrderGoodTotal(good, sbNames, 1);
                packageCustomerStatistics(customerStatisticResultDtos1,customers,CustomerStatisticEnum.oldVendorOrderMoney.getId());

                //平台供应商订单金额
                List<CustomerStatisticResultDto> customerStatisticResultDtos = CustomerStatisticsJdbcUtil.queryVendorOrderGoodTotal(good, sbNames, 0);
                packageCustomerStatistics(customerStatisticResultDtos,customers,CustomerStatisticEnum.plateVendorOrderMoney.getId());

                //询价单询价方式为邀请或者邀请且全平台公开询价商品条数
                List<CustomerStatisticResultDto> inquiryVendors = CustomerStatisticsJdbcUtil.queryInquiryVendorScope(good, sbNames);
                packageCustomerStatistics(inquiryVendors,customers,CustomerStatisticEnum.vendorScopeGoodNum.getId());


                //定标商品条数
                List<CustomerStatisticResultDto> customerStatisticResultDtos2 = CustomerStatisticsJdbcUtil.queryInquiryGoodPicketagedNum(good, sbNames);
                packageCustomerStatistics(customerStatisticResultDtos2,customers,CustomerStatisticEnum.picketagedGoodCount.getId());

                //报价次数
                List<CustomerStatisticResultDto> customerStatisticResultDtos3 = CustomerStatisticsJdbcUtil.querySumQuotationNum(good, sbNames);
                packageCustomerStatistics(customerStatisticResultDtos3,customers,CustomerStatisticEnum.quotationCount.getId());
                //平均报价次数

                packageAverageQuotation(customerStatisticResultDtos3,inquiryGoods,customers);
                if (customers != null && customers.size() > 0){
                    customers.forEach(item->{
                        params.add(BeanUtils.bean2Map(item));
                    });
                }

            } else {
            }
        } catch (Exception e) {
            log.info("查询出错", e);
        }
        BoResultFormat.resultFormat(params, ModelConst.CUSTOMER_STATISTICS);
        BOList bOList = new BOList();
        bOList.setData(params);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.CUSTOMER_STATISTICS);
        return com.alibaba.cola.dto.SingleResponse.of(bOList);
    }



    @Path("exportCustomerStatistics")
    @POST
    @Operation(summary = "新版客户数据统计导出",tags = CUSTOM_SERVICE)
    public SingleResponse exportCustomerStatistics(@Parameter CustomerStatisticsDto good){
        ReportType reportType = ReportType.get(good.getFileType());
        SingleResponse<BOList> boList = queryCustomerStatistics(good);
        if (boList != null && boList.getData() != null && boList.getData().getData().size() > 0){
            List<Map<String, Object>> datas = boList.getData().getData();
            String exportField = "{\"inquiry_good_num\":\"inquiry_good_num\",\"clarify_record_count\":\"clarify_record_count\",\"quote_count_num\":\"quote_count_num\",\"invite_code_num\":\"invite_code_num\",\"order_goods\":\"order_goods\",\"platform_num\":\"platform_num\",\"old_platformNum\":\"old_platformNum\",\"orderMoney\":\"orderMoney\",\"oldVendorOrderMoney\":\"oldVendorOrderMoney\",\"plateVendorOrderMoney\":\"plateVendorOrderMoney\",\"vendorScopeGoodNum\":\"vendorScopeGoodNum\",\"picketagedGoodCount\":\"picketagedGoodCount\",\"quotationCount\":\"quotationCount\",\"averageQuotationCount\":\"averageQuotationCount\",\"name\":\"name\"}";
            JSONObject exportJson = JSON.parseObject(exportField);
            List<Map<String, Object>> fileData = datas.stream().map(m -> {
                Map<String, Object> mf = new HashMap<>();
                for (String key : exportJson.keySet()) {
                    mf.put(exportJson.getString(key), m.get(key));
                }
                return mf;
            }).collect(Collectors.toList());

            ReportUtils.exportReport("sales-data-statistics-report", reportType.getId(), fileData);

            return SingleResponse.buildSuccess();



        }else{
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }

    }

    private void packageAverageQuotation(List<CustomerStatisticResultDto> customerStatisticResultDtos3, List<CustomerStatisticResultDto> inquiryGoods, List<CustomerStatisticInfoDto> customers) {
        if ((customerStatisticResultDtos3 == null || customerStatisticResultDtos3.size() == 0)
                || (inquiryGoods == null || inquiryGoods.size() == 0)
                || (customers == null || customers.size() == 0)

        ) {
            Map<String,String> param3 = new HashMap<>();

            customerStatisticResultDtos3.forEach(item->{
                param3.put(item.getName(),item.getTotal());
            });

            Map<String,String> inquiryGoodsParam = new HashMap<>();

            inquiryGoods.forEach(item->{
                inquiryGoodsParam.put(item.getName(),item.getTotal());
            });

            customers.forEach(item->{
                String orgName = item.getName();
                if (param3.containsKey(orgName) && inquiryGoodsParam.containsKey(orgName)){
                    String quotationCount = param3.get(orgName);
                    String inquiryGoodsCount = inquiryGoodsParam.get(orgName);
                    if(StringUtils.isNotBlank(quotationCount) && StringUtils.isNotBlank(inquiryGoodsCount)){
                        BigDecimal quotationCountNo =new BigDecimal(quotationCount);
                        BigDecimal inquiryGoodsNo =new BigDecimal(inquiryGoodsCount);
                        BigDecimal divide = quotationCountNo.divide(inquiryGoodsNo);
                        item.setAverageQuotationCount(divide);
                    }

                }

            });


        }


    }




    private void packageCustomerStatistics(List<CustomerStatisticResultDto> inquiryGoods, List<CustomerStatisticInfoDto> customers,Integer type) {
        if (customers != null && customers.size() >0){
            customers.forEach(item->{
                String name = (String) item.getName();
                inquiryGoods.forEach(item2->{
                    String customer_organization_name = item2.getName();
                    if (StringUtils.equals(name,customer_organization_name)){
                        String total = item2.getTotal();
                        if (type == CustomerStatisticEnum.inquiry_good_num.getId()){
                            item.setInquiry_good_num(total);
                        }else if (type ==  CustomerStatisticEnum.clarify_record_count.getId()){
                            item.setClarify_record_count(total);
                        }else if (type ==  CustomerStatisticEnum.quote_count_num.getId()){
                            item.setQuote_count_num(total);
                        }else if (type ==  CustomerStatisticEnum.invite_code_num.getId()){
                            item.setInvite_code_num(total);
                        }else if (type ==  CustomerStatisticEnum.order_goods.getId()){
                            item.setOrder_goods(total);
                        }else if (type ==  CustomerStatisticEnum.platform_num.getId()){
                            item.setPlatform_num(total);
                        }else if (type ==  CustomerStatisticEnum.old_platformNum.getId()){
                            item.setOld_platformNum(total);
                        }

                    }
                });
            });
        }
    }


    @Path("queryCustomerTradeNumStatistics")
    @POST
    @Operation(summary = "客户交易量统计",tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> queryCustomerTradeNumStatistics(@Parameter CustomerStatisticsDto good){
        //查询客户组织名称
        List<Map<String,Object>> params = new ArrayList<>();
        PageObject<Map<String, Object>> pageObject = new PageObject<Map<String, Object>>();

        List<Map<String, Object>> customers = new ArrayList<>();
        Integer count = 0;
        try {
            Integer pageCurrent = good.getPageCurrent() == null ? 1 : good.getPageCurrent();
            Integer pageSize = good.getPageSize() == null ? 10 : good.getPageSize();
            // 设置当前页
            good.setPageCurrent(pageCurrent);
            // 设置每页显示的条数
            pageObject.setPageSize(pageSize);
            // 设置总记录数

            count = CustomerStatisticsJdbcUtil.queryAllCustomerCount(good);
            log.info("总条数:{}" + count);
            pageObject.setRowCount(count);
            pageObject.setPageCount(0);
            if (count != 0) {
                // 设置总页数
                int pageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                pageObject.setPageCount(pageNum);
                // 设置每页显示数据集合
                // 开始的记录数
                int start = (pageCurrent - 1) * pageSize;
                System.out.println(start + "-" + pageSize);
                customers = CustomerStatisticsJdbcUtil.queryAllCustomerInfos(good, start, pageSize);
                boolean isGroupByTime = false;
                packageCustomerTradeStatistic(good, customers,isGroupByTime);
            }
        } catch (Exception e) {
            log.info("查询出错", e);
        }
        BoResultFormat.resultFormat(customers, "dggo2p5nhbls");
        BOList bOList = new BOList();
        bOList.setData(customers);
        bOList.setTotal(count);
        bOList.setSchemaCode("dggo2p5nhbls");
        return com.alibaba.cola.dto.SingleResponse.of(bOList);
    }

    private void packageCustomerTradeStatistic(CustomerStatisticsDto good, List<Map<String, Object>> customers,boolean isGroupByTime) {
        StringBuffer sbNames = new StringBuffer();
        if (customers != null && customers.size() > 0){
            customers.forEach(item->{
                String name = (String) item.get("name");
                if (StringUtils.isNotBlank(name)){
                    sbNames.append(name);
                    sbNames.append(",");
                }
            });
        }
        sbNames.deleteCharAt(sbNames.length() - 1);
        //原有供应商报价数量
        List<CustomerStatisticResultDto> vendorQuotationNums = CustomerStatisticsJdbcUtil.queryVendorQuotationNum(sbNames, good,isGroupByTime);
        packageCustomerStatisticList(vendorQuotationNums, customers,"quotationOldVendor");

        //平台报价数量
        List<CustomerStatisticResultDto> plateQuotationNums = CustomerStatisticsJdbcUtil.queryPlateQuotationNum(sbNames, good,isGroupByTime);
        packageCustomerStatisticList(plateQuotationNums, customers,"quotationPlateformVendor");

        //原有供应商定标数量
        List<CustomerStatisticResultDto> vendorDingbiaoNums = CustomerStatisticsJdbcUtil.queryVendorDingbiaoNum(sbNames, good,isGroupByTime);
        packageCustomerStatisticList(vendorDingbiaoNums, customers,"dingbiaoOldVendor");


        //平台供应商定标数量
        List<CustomerStatisticResultDto> plateVendorDingbiaoNums = CustomerStatisticsJdbcUtil.queryPlateVendorDingbiaoNum(sbNames, good,isGroupByTime);
        packageCustomerStatisticList(plateVendorDingbiaoNums, customers,"dingbiaoPlateformVendor");

        //询价商品数量)
        List<CustomerStatisticResultDto> customerInquiryGoodNums = CustomerStatisticsJdbcUtil.queryCustomerInquiryGoodNum(sbNames, good,isGroupByTime);
        packageCustomerStatisticList(customerInquiryGoodNums, customers,"inquiryGoodCount");
        //未报价商品数
        List<CustomerStatisticResultDto>  unQuotationGoodNums = CustomerStatisticsJdbcUtil.queryUnQuotationGoodNum(sbNames, good,isGroupByTime);
        packageCustomerStatisticList(unQuotationGoodNums, customers,"unQuotation");

        //原有供应商订单商品数量，原有供应商退货金额
        List<Map<String,Object>>  oldVendorGoods = CustomerStatisticsJdbcUtil.queryVendorOrderGoodNum(sbNames, good,null,isGroupByTime);
        packageCustomerStatisticsForMap(oldVendorGoods, customers,"orderGoodOldVendor","returnOldVendor");

        //平台供应商订单商品数量 平台供应商退货金额
        List<Map<String,Object>>  vendorGoods = CustomerStatisticsJdbcUtil.queryVendorOrderGoodNum(sbNames, good,"not",isGroupByTime);
        packageCustomerStatisticsForMap(vendorGoods, customers,"orderGoodPlateformVendor","returnPlateformVendor");
        //订单数量
        List<CustomerStatisticResultDto>  orderNums = CustomerStatisticsJdbcUtil.queryOrderNum(sbNames, good,isGroupByTime);
        packageCustomerStatisticList(orderNums, customers,"orderNum");

        //查询项目负责人
        StringBuffer sb = new StringBuffer();
        sb.append("客服部");
        sb.append(",");
        sb.append("项目管理部");
        sb.append(",");
        sb.append("驻场部");
        List<UserDto> userDtos = CustomerStatisticsJdbcUtil.queryCustomerUserDepartment(sb.toString());
        Map<String,Object>param = new HashMap<>();
        if (userDtos != null && userDtos.size() > 0 ){
            userDtos.forEach(item->{
                String department_name = item.getDepartment_name();
                String username = item.getUsername();
                if ((StringUtils.equals(department_name,"项目管理部")
                        || StringUtils.equals(department_name,"驻场部")
                        || StringUtils.equals(department_name,"客服部")&&StringUtils.isNotBlank(username))){
                    param.put(department_name,username);
                }
            });
        }
        String prjectUserName = (String) param.get("项目管理部");
        if(StringUtils.isNotBlank(prjectUserName)){
            List<Map<String,Object>>  projectManagers = CustomerStatisticsJdbcUtil.queryProjectManager(prjectUserName,sbNames);
            packageCustomerStatisticsForUser(projectManagers, customers,"projectManager");
        }
        String customerUserName = (String) param.get("客服部");
        if(StringUtils.isNotBlank(customerUserName)){
            List<Map<String,Object>>  customerUserNames = CustomerStatisticsJdbcUtil.queryProjectManager(customerUserName,sbNames);
            packageCustomerStatisticsForUser(customerUserNames, customers,"kefuUser");
        }
        String zhuchangUserName = (String) param.get("驻场部");
        if(StringUtils.isNotBlank(customerUserName)){
            List<Map<String,Object>>  zhuchangUserNames = CustomerStatisticsJdbcUtil.queryProjectManager(zhuchangUserName,sbNames);
            packageCustomerStatisticsForUser(zhuchangUserNames, customers,"zhuchangUser");
        }
    }
    private  List<Map<String,Object>>  packageCustomerTradeStatisticByTime(CustomerStatisticsDto good, List<Map<String, Object>> customers,boolean isGroupByTime) {
        List<Map<String,Object>> list = new ArrayList<>();
        StringBuffer sbNames = new StringBuffer();
        if (customers != null && customers.size() > 0){
            customers.forEach(item->{
                String name = (String) item.get("name");
                if (StringUtils.isNotBlank(name)){
                    sbNames.append(name);
                    sbNames.append(",");
                }
            });
            sbNames.deleteCharAt(sbNames.length() - 1);
        }

        //报价次数
        List<CustomerStatisticResultDto> baoojiaResults = CustomerStatisticsJdbcUtil.queryBaojiaCount(sbNames, good);

        //询价次数
        List<CustomerStatisticResultDto> inquiryResults = CustomerStatisticsJdbcUtil.queryInquiryNum(sbNames, good);

        //定标次数
        List<CustomerStatisticResultDto> dingbiaoList = CustomerStatisticsJdbcUtil.queryDingbiaoCount(sbNames, good);

        //订单数量
        List<CustomerStatisticResultDto> orderNums = CustomerStatisticsJdbcUtil.queryOrderNum(sbNames, good);

        //订单商品
        List<CustomerStatisticResultDto> orderGoodNums = CustomerStatisticsJdbcUtil.queryOrderGoodNum(sbNames, good);

        //原有供应商订单商品数量，原有供应商退货金额
        List<Map<String,Object>>  oldVendorGoods = CustomerStatisticsJdbcUtil.queryVendorOrderGoodNum(sbNames, good,null,isGroupByTime);

        //平台供应商订单商品数量 平台供应商退货金额
        List<Map<String,Object>>  vendorGoods = CustomerStatisticsJdbcUtil.queryVendorOrderGoodNum(sbNames, good,"not",isGroupByTime);

        packageCustomerStatisticListByTime(list,baoojiaResults, "inquiryGoodCount");
        packageCustomerStatisticListByTime(list,inquiryResults,"inquiryCount");
        packageCustomerStatisticListByTime(list,dingbiaoList, "scalingCount");
        packageCustomerStatisticListByTime(list,orderNums, "orderCount");
        packageCustomerStatisticListByTime(list,orderGoodNums, "orderGoodsCount");
        packageCustomerStatisticsByTimeForMap2(list,oldVendorGoods, "vendorOrderAmount","vendorOrderReturnAmount");
        packageCustomerStatisticsByTimeForMap2(list,vendorGoods, "platformVendorOrderAmount","platformVendorOrderReturnAmount");
        packageCustomerStatisticListByTime(list,orderNums,"orderNum");
        list.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("time"))));  //正序



        //查询项目负责人result.sort(Comparator.comparing((Map<String, Object> h) -> ((String) h.get("lastOnlineTime"))));  //正序
        StringBuffer sb = new StringBuffer();
        sb.append("客服部");
        sb.append(",");
        sb.append("项目管理部");
        sb.append(",");
        sb.append("驻场部");
        List<UserDto> userDtos = CustomerStatisticsJdbcUtil.queryCustomerUserDepartment(sb.toString());
        Map<String,Object>param = new HashMap<>();
        if (userDtos != null && userDtos.size() > 0 ){
            userDtos.forEach(item->{
                String department_name = item.getDepartment_name();
                String username = item.getUsername();
                if ((StringUtils.equals(department_name,"项目管理部")
                        || StringUtils.equals(department_name,"驻场部")
                        || StringUtils.equals(department_name,"客服部")&&StringUtils.isNotBlank(username))){
                    param.put(department_name,username);
                }
            });
        }
        String prjectUserName = (String) param.get("项目管理部");
        if(StringUtils.isNotBlank(prjectUserName)){
            List<Map<String,Object>>  projectManagers = CustomerStatisticsJdbcUtil.queryProjectManager(prjectUserName,sbNames);
            packageCustomerStatisticsForUser(projectManagers, customers,"projectManagerName");
        }
        String customerUserName = (String) param.get("客服部");
        if(StringUtils.isNotBlank(customerUserName)){
            List<Map<String,Object>>  customerUserNames = CustomerStatisticsJdbcUtil.queryProjectManager(customerUserName,sbNames);
            packageCustomerStatisticsForUser(customerUserNames, customers,"kefcustomerServiceNameUser");
        }
        String zhuchangUserName = (String) param.get("驻场部");
        if(StringUtils.isNotBlank(customerUserName)){
            List<Map<String,Object>>  zhuchangUserNames = CustomerStatisticsJdbcUtil.queryProjectManager(zhuchangUserName,sbNames);
            packageCustomerStatisticsForUser(zhuchangUserNames, customers,"residentName");
        }
        return  list;
    }

    private void packageCustomerStatisticListByTime(List<Map<String,Object>> list,List<CustomerStatisticResultDto> customerInquiryGoodNums, String key) {
        Set<String> set  = new HashSet<>();
        if (customerInquiryGoodNums != null && customerInquiryGoodNums.size() > 0 ){
            customerInquiryGoodNums.forEach(item->{
                String name = item.getName();
                String time = item.getTime();
                if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(time)){
                    String packageInfo = name + ";" + time;
                    if(!set.contains(packageInfo)){
                        set.add(packageInfo);
                        Map<String,Object> param = new HashMap<>();
                        converCommonMap(param);
                        param.put("name",name);
                        param.put("time",time);
                        Integer count = item.getCount() == null ? 0: item.getCount();
                        param.put(key,count);
                        list.add(param);
                    }else{
                        list.forEach(item2->{
                            String item_name = (String) item2.get("name");
                            String item_time = (String) item2.get("time");
                            if (StringUtils.equals(item_name,name) && StringUtils.equals(item_time,time)){
                                Integer count = item.getCount() == null ? 0: item.getCount();
                                item2.put(key,count);
                            }
                        });
                    }
                }
            });
        }
    }

    public void converCommonMap(Map<String,Object> param){
        param.put("projectManagerName",null);
        param.put("residentName",null);
        param.put("customerServiceName",null);
        param.put("time",null);
        param.put("inquiryCount",0);
        param.put("quotationCount",0);
        param.put("scalingCount",0);
        param.put("orderCount",0);
        param.put("orderGoodsCount",0);

        param.put("vendorOrderAmount",0.0);
        param.put("platformVendorOrderAmount",0.0);
        param.put("vendorOrderReturnAmount",0.0);
        param.put("platformVendorOrderReturnAmount",0.0);
        param.put("vendorOrderActualAmount",0.0);
        param.put("platformVendorOrderActualAmount",0.0);

    }

    private void packageCustomerStatisticsForUser(List<Map<String, Object>> datas, List<Map<String, Object>> customers, String key) {
        if (customers != null && customers.size() >0 ){
            if (datas != null && datas.size() > 0){
                customers.forEach(item->{
                    String name = (String) item.get("name");
                    datas.forEach(item2->{
                        String customer_organization_name = (String) item2.get("name");
                        if (StringUtils.equals(name,customer_organization_name)){
                            String fullname = (String) item2.get("fullname");
                            item.put(key,fullname);
                        }
                    });
                });
            }
        }
    }

    public void packageCustomerStatisticList(List<CustomerStatisticResultDto> datas, List<Map<String, Object>> customers, String key) {
        if (customers != null && customers.size() >0 ){
            if (datas != null && datas.size() > 0){
                customers.forEach(item->{
                    String name = (String) item.get("name");
                    datas.forEach(item2->{
                        String customer_organization_name = item2.getName();
                        if (StringUtils.equals(name,customer_organization_name)){
                            Integer count = item2.getCount() == null ? 0: item2.getCount();
                            item.put(key,count);
                        }
                    });
                });
            }else{
                customers.forEach(item->{
                    item.put(key,0);
                });
            }
        }

    }
    private void packageCustomerStatisticsByTimeForMap2(List<Map<String,Object>> list,List<Map<String,Object>> customerInquiryGoodNums, String keyOne,String keyTwo) {
        Set<String> set  = new HashSet<>();
        if (customerInquiryGoodNums != null && customerInquiryGoodNums.size() > 0 ){
            customerInquiryGoodNums.forEach(item->{
                String name = (String) item.get("name");
                String time = (String) item.get("tme");
                if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(time)){
                    String packageInfo = name + ";" + time;
                    if(!set.contains(packageInfo)){
                        set.add(packageInfo);
                        Map<String,Object> param = new HashMap<>();
                        param.put("name",name);
                        param.put("time",time);
                        converCommonMap(param);
                        Double refundAmount = (Double) item.get("refundAmount")== null ? 0.0 :(Double) item.get("refundAmount") ;
                        Double total = (Double) item.get("total")== null ? 0.0 :(Double) item.get("total") ;
                        param.put(keyOne,total);
                        param.put(keyTwo,refundAmount);
                        list.add(param);
                    }else{
                        list.forEach(item2->{
                            String item_name = (String) item2.get("name");
                            String item_time = (String) item2.get("time");
                            if (StringUtils.equals(item_name,name) && StringUtils.equals(item_time,time)){
                                Double refundAmount = (Double) item.get("refundAmount")== null ? 0.0 :(Double) item.get("refundAmount") ;
                                Double total = (Double) item.get("total")== null ? 0.0 :(Double) item.get("total") ;
                                item2.put(keyOne,total);
                                item2.put(keyTwo,refundAmount);
                            }
                        });
                    }
                }
            });
        }




    }




    public void packageCustomerStatisticsForMap(List<Map<String,Object>> datas, List<Map<String, Object>> customers, String keyOne,String keyTwo) {

        if (customers != null && customers.size() >0 ){
            if (datas != null && datas.size() > 0){
                customers.forEach(item->{
                    String name = (String) item.get("name");
                    datas.forEach(item2->{
                        String customer_organization_name = (String) item2.get("name");
                        if (StringUtils.equals(name,customer_organization_name)){
                            Integer quantity = (Integer) item2.get("quantity") == null ? 0 :(Integer) item2.get("quantity");
                            Integer refundAmount = (Integer) item2.get("refundAmount")== null ? 0 :(Integer) item2.get("refundAmount");
                            item2.put(keyOne,quantity);
                            item2.put(keyTwo,refundAmount);


                        }
                    });
                });
            }else{
                customers.forEach(item->{
                    item.put(keyOne,0);
                    item.put(keyTwo,0);
                });
            }
        }

    }
    @Path("exportPlateTradeResult")
    @POST
    @Operation(summary = "客户交易量统计-导出平台销售数据",tags = CUSTOM_SERVICE)
    public com.authine.hermes.app.launcher.response.SingleResponse<Object> exportPlateTradeResult(@Parameter CustomerStatisticsDto good){
        List<Map<String, Object>> customers = CustomerStatisticsJdbcUtil.queryAllCustomerInfos(good, null, null);
        List<Map<String, Object>> list = packageCustomerTradeStatisticByTime(good, customers, true);
        if (list != null && list.size() > 0){
            list.forEach(v->{
                Double plateamount = (Double) v.get("platformVendorOrderAmount");
                Double plateReturnAmount = (Double) v.get("platformVendorOrderReturnAmount");
                double sub = CustomerStatisticsJdbcUtil.sub(plateamount, plateReturnAmount);
                v.put("platformVendorOrderActualAmount",sub);

                Double vendorOrderAmount = (Double) v.get("vendorOrderAmount");
                Double vendorOrderReturnAmount = (Double) v.get("vendorOrderReturnAmount");
                double subold = CustomerStatisticsJdbcUtil.sub(vendorOrderAmount, vendorOrderReturnAmount);
                v.put("vendorOrderActualAmount",subold);
            });
            ReportRecord record = ReportRecord.builder()
                    .code("platform_sales_statistics_report")
                    .type(Optional.ofNullable(FileExportEnum.get(good.getFileType())).orElseThrow(()->new BizException("文件类型不支持")).getCode())
                    .data(list)
                    .build();
            Map singleResponse = RestTemplateUtil.rest(Objects.requireNonNull(PmUtil.getUrl(systemManagement)).concat(EXPORT_REPORT_URL), record, HttpMethod.POST);
            com.alibaba.cola.dto.SingleResponse response = BoUtils.Map2Bo(singleResponse, com.alibaba.cola.dto.SingleResponse.class);
            com.alibaba.cola.exception.Assert.isTrue(response.isSuccess(),response.getErrMessage());
            return com.authine.hermes.app.launcher.response.SingleResponse.of(singleResponse.get("data"));
        }
        return null;
    }



    @Path("exportCustomerStatisticsInquiryGood")
    @POST
    @Operation(summary = "客户交易量统计-导出询价数据",tags = CUSTOM_SERVICE)
    public SingleResponse exportCustomerStatisticsInquiryGood(@Parameter CustomerStatisticsDto good){
        ReportType reportType = ReportType.get(good.getFileType());
        List<Map<String, Object>> maps = CustomerStatisticsJdbcUtil.queryInquiryGoodExport(good);
        if (maps != null && maps.size() > 0){
            maps.forEach(item->{
                Date time = (Date) item.get("time");
                item.put("time",DateUtil.formatDateTime(time));

                Date expire = (Date) item.get("expire");
                item.put("expire",DateUtil.formatDateTime(expire));
            });
            ReportUtils.exportReport("work_bench_customer_transaction_inquiry_report", reportType.getId(), maps);
            return SingleResponse.buildSuccess();
        }else{
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }
    }
    @Path("exportCommonPurchaseStatistics")
    @POST
    @Operation(summary = "客户交易量统计-导出公采结算数据",tags = CUSTOM_SERVICE)
    public SingleResponse exportCommonPurchaseStatistics(@Parameter CustomerStatisticsDto good){
        if ((StringUtils.isNotBlank(good.getOrgIds()) && StringUtils.isEmpty(good.getOrgName()))
        || (StringUtils.isNotBlank(good.getOrgName()) && StringUtils.isEmpty(good.getOrgIds()))
        ){
            return SingleResponse.buildFailure("-1","参数不完整");
        }
        List<String> orgNames = null;
        ReportType reportType = ReportType.get(good.getFileType());

        List<OrgInfoDto> orgs = CustomerStatisticsJdbcUtil.queryOrganizationInfo(good);
        List<OrgInfoDto> children = new ArrayList<>();
        childOrgTrees(orgs,good.getOrgIds(),children);
        if (!CollectionUtils.isEmpty(children)){
            orgNames = children.stream().map(e->e.getName()).collect(Collectors.toList());
            if (StringUtils.isNotBlank(good.getOrgName())){
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(orgNames) && !orgNames.contains(good.getOrgName())){
                    orgNames.add(good.getOrgName());
                }
            }
        }
        StringBuffer sb = new StringBuffer();
        if (orgNames != null && orgNames.size() > 0) {
            orgNames.forEach(item->{
                sb.append(item);
                sb.append(",");
            });
            sb.deleteCharAt(sb.length() - 1);
        }
        //获取订单商品id
        String  order_good_ids = CustomerStatisticsJdbcUtil.queryCommonPurchaseStatistics(good,sb);

        //获取结算数据
        List<Map<String, Object>> maps = CustomerStatisticsJdbcUtil.queryCommonPurchase(good, order_good_ids);
        if (maps != null  && maps.size() > 0){
            ReportUtils.exportReport("client_settlement_data_report", reportType.getId(), maps);
            return SingleResponse.buildSuccess();
        }else{
            return SingleResponse.buildFailure("-1", "未获取到下载数据");
        }
    }

    private void childOrgTrees(List<OrgInfoDto> organizationDtoList, String pid,List<OrgInfoDto> children) {
        for (OrgInfoDto org: organizationDtoList) {
            String selectorFormat = org.getParent_id();
            SelectorFormat format = JSONObject.parseObject(selectorFormat, SelectorFormat.class);
            if(format != null) {
                String parentId = format.getId();
                //遍历出父id等于参数的id，add进子节点集合
                if (pid.equalsIgnoreCase(parentId)) {
                    //递归遍历下一级
                    children.add(org);
                    childOrgTrees(organizationDtoList, org.getId(),children);
                }
            }

        }
    }

    @Path("querySaleDataStatistics")
    @POST
    @Operation(summary = "销售数据对比统计",tags = CUSTOM_SERVICE)
    public  SingleResponse querySaleDataStatistics(CustomerStatisticsDto good){

        String startTime = good.getStartTime();
        String endTime = good.getEndTime();
        String secondStartTime = good.getSecondStartTime();
        String secondEndTime = good.getSecondEndTime();
        if(StringUtils.isBlank(endTime) ||
        StringUtils.isBlank(startTime)||
        StringUtils.isBlank(secondStartTime) ||
        StringUtils.isBlank(secondEndTime )
        ){
            return SingleResponse.buildFailure("1","缺少参数");
        }

        PageObject<Map<String, Object>> pageObject = new PageObject<Map<String, Object>>();

        List<Map<String, Object>> users = new ArrayList<>();
        Integer count = 0;
        try {
            Integer pageCurrent = good.getPageCurrent() == null ? 1 : good.getPageCurrent();
            Integer pageSize = good.getPageSize() == null ? 10 : good.getPageSize();
            // 设置当前页
            good.setPageCurrent(pageCurrent);
            // 设置每页显示的条数
            pageObject.setPageSize(pageSize);
            // 设置总记录数

            count = CustomerStatisticsJdbcUtil.queryAllPlateUserCount(good);
            log.info("总条数:{}" + count);
            pageObject.setRowCount(count);
            pageObject.setPageCount(0);
            if (count != 0) {
                // 设置总页数
                int pageNum = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;
                pageObject.setPageCount(pageNum);
                // 设置每页显示数据集合
                // 开始的记录数
                int start = (pageCurrent - 1) * pageSize;
                System.out.println(start + "-" + pageSize);
                users =  CustomerStatisticsJdbcUtil.queryAllPlateUserList(good, start, pageSize);

                List<Map<String,Object>> list = CustomerStatisticsJdbcUtil.queryAllPlateOrganization();

                List<Map<String,Object>> secondList = list.stream().map(e -> {return e ;}).collect(Collectors.toList());


                boolean isGroupByTime = false;
                packageCustomerTradeStatistic(good, list,isGroupByTime);
                good.setStartTime(secondStartTime);
                good.setEndTime(secondEndTime);
                packageCustomerTradeStatistic(good, secondList,isGroupByTime);

                List<Map<String,Object>> totalList = new ArrayList<>();


                if (users != null && users.size() > 0){
                    users.forEach(item->{
                        String name = (String) item.get("name");
                        String[] split = name.split(",");
                        if (split.length > 1){
                            for (int index = 0; index < split.length; index++) {
                                getPlateUserStatistic(totalList,list,item,index+1,split.length,good,"first");
                                getPlateUserStatistic(totalList,secondList,item,index+1,split.length,good,"second");
                            }
                        }

                    });
                }
            }
        } catch (Exception e) {
            log.info("查询出错", e);
        }
        BoResultFormat.resultFormat(users, "dhbp0xty2v40");
        BOList bOList = new BOList();
        bOList.setData(users);
        bOList.setTotal(count*2);
        bOList.setSchemaCode("dhbp0xty2v40");
        return com.alibaba.cola.dto.SingleResponse.of(bOList);
    }

    /**
     *
     * @param totalList 总条数
     * @param list 业务数据几个
     * @param userItem 用户信息
     * @param index  排序
     * @param length 分组列数
     * @param good 查询参数
     * @param type 类型
     */
    private void getPlateUserStatistic(List<Map<String, Object>> totalList, List<Map<String, Object>> list, Map<String, Object> userItem,
                                       int index, int length, CustomerStatisticsDto good, String type) {
        if (length > 1 && index > 1 && index <=  length){
            //说明一个用户对应多个组织机构 ,相加,但是业务数据不一定存在
            addIntoTotalItem(userItem,totalList,list,good,type,length);
        }else{
            //
            addItem(userItem,totalList,list,good,type,length);
        }
    }

    private void addItem(Map<String, Object> userItem, List<Map<String, Object>> totals, List<Map<String, Object>> list, CustomerStatisticsDto good, String type, int length) {
        Map<String,Object> param = new HashMap<>();
        if (list != null && list.size()>0){
            boolean flag =  false;
            Map<String,Object> total =new HashMap<>();

            for (Map<String,Object> service : list) {
                String orgName = (String) service.get("name");
                String orgNameInfo = (String) userItem.get("name");
                if (StringUtils.equals(orgNameInfo,orgName)){
                    flag = true;
                    param = service;
                    break;
                }
            }
            String timeZone = "";
            if (StringUtils.equals("type", "first")) {
                timeZone = good.getStartTime() + "至" + good.getEndTime();
            } else {
                timeZone = good.getSecondStartTime() + "至" + good.getSecondEndTime();
            }
            total.put("timeZone", timeZone);
            total.put("type",type);
            total.put("saleUserName", userItem.get("userName"));
            Integer total_inquiryGoodCount = (Integer) total.get("inquiryGoodCount") == null ? 0 : (Integer) total.get("inquiryGoodCount");
            Integer total_quotationOldVendor = (Integer) total.get("quotationOldVendor")== null ? 0 : (Integer) total.get("quotationOldVendor");
            Integer total_quotationPlateformVendor =(Integer)  total.get("quotationPlateformVendor")== null ? 0 : (Integer) total.get("quotationPlateformVendor");
            Integer total_unQuotation =(Integer)  total.get("unQuotation")== null ? 0 : (Integer) total.get("unQuotation");
            Integer total_dingbiaoOldVendor = (Integer) total.get("dingbiaoOldVendor")== null ? 0 : (Integer) total.get("dingbiaoOldVendor");
            Integer total_dingbiaoPlateformVendor =(Integer)  total.get("dingbiaoPlateformVendor")== null ? 0 : (Integer) total.get("dingbiaoOldVendor");
            Integer total_orderGoodOldVendor = (Integer) total.get("orderGoodOldVendor")== null ? 0 : (Integer) total.get("orderGoodOldVendor");
            Integer total_orderGoodPlateformVendor =(Integer)  total.get("orderGoodPlateformVendor")== null ? 0 : (Integer) total.get("orderGoodPlateformVendor");
            Integer total_orderNum = (Integer) total.get("orderNum")== null ? 0 : (Integer) total.get("orderNum");
            BigDecimal total_orderMoneyOldVendor = (BigDecimal) total.get("orderMoneyOldVendor")== null ? new BigDecimal(0) : (BigDecimal) total.get("orderMoneyOldVendor");
            BigDecimal total_orderMoneyPlateformVendor = (BigDecimal)total.get("orderMoneyPlateformVendor")== null ? new BigDecimal(0) : (BigDecimal) total.get("orderMoneyPlateformVendor");
            BigDecimal total_returnPlateformVendor =(BigDecimal) total.get("returnPlateformVendor")== null ? new BigDecimal(0) : (BigDecimal) total.get("returnPlateformVendor");
            BigDecimal total_returnOldVendor =(BigDecimal) total.get("returnOldVendor")== null ? new BigDecimal(0) : (BigDecimal) total.get("returnOldVendor");

            if (flag){
                Integer inquiryGoodCount = (Integer) param.get("inquiryGoodCount") == null ? 0 : (Integer) param.get("inquiryGoodCount");
                Integer quotationOldVendor = (Integer) param.get("quotationOldVendor")== null ? 0 : (Integer) param.get("quotationOldVendor");
                Integer quotationPlateformVendor =(Integer)  param.get("quotationPlateformVendor")== null ? 0 : (Integer) param.get("quotationPlateformVendor");
                Integer unQuotation =(Integer)  param.get("unQuotation")== null ? 0 : (Integer) param.get("unQuotation");
                Integer dingbiaoOldVendor = (Integer) param.get("dingbiaoOldVendor")== null ? 0 : (Integer) param.get("dingbiaoOldVendor");
                Integer dingbiaoPlateformVendor =(Integer)  param.get("dingbiaoPlateformVendor")== null ? 0 : (Integer) param.get("dingbiaoOldVendor");
                Integer orderGoodOldVendor = (Integer) param.get("orderGoodOldVendor")== null ? 0 : (Integer) param.get("orderGoodOldVendor");
                Integer orderGoodPlateformVendor =(Integer)  param.get("orderGoodPlateformVendor")== null ? 0 : (Integer) param.get("orderGoodPlateformVendor");
                Integer orderNum = (Integer) param.get("orderNum")== null ? 0 : (Integer) param.get("orderNum");
                BigDecimal orderMoneyOldVendor = (BigDecimal) param.get("orderMoneyOldVendor")== null ? new BigDecimal(0) : (BigDecimal) param.get("orderMoneyOldVendor");
                BigDecimal orderMoneyPlateformVendor = (BigDecimal)param.get("orderMoneyPlateformVendor")== null ? new BigDecimal(0) : (BigDecimal) param.get("orderMoneyPlateformVendor");
                BigDecimal returnPlateformVendor =(BigDecimal) param.get("returnPlateformVendor")== null ? new BigDecimal(0) : (BigDecimal) param.get("returnPlateformVendor");
                BigDecimal returnOldVendor =(BigDecimal) param.get("returnOldVendor")== null ? new BigDecimal(0) : (BigDecimal) param.get("returnOldVendor");

                total.put("inquiryGoodCount",inquiryGoodCount+total_inquiryGoodCount);
                total.put("quotationOldVendor",quotationOldVendor+total_quotationOldVendor);
                total.put("quotationPlateformVendor",quotationPlateformVendor+total_quotationPlateformVendor);
                total.put("unQuotation",unQuotation+total_unQuotation);
                total.put("dingbiaoOldVendor",dingbiaoOldVendor+total_dingbiaoOldVendor);
                total.put("dingbiaoPlateformVendor",dingbiaoPlateformVendor+total_dingbiaoPlateformVendor);
                total.put("orderGoodOldVendor",orderGoodOldVendor+total_orderGoodOldVendor);
                total.put("orderGoodPlateformVendor",orderGoodPlateformVendor+total_orderGoodPlateformVendor);
                total.put("orderNum",orderNum+total_orderNum);
                total.put("orderMoneyOldVendor",orderMoneyOldVendor.add(total_orderMoneyOldVendor));
                total.put("orderMoneyPlateformVendor",orderMoneyPlateformVendor.add(total_orderMoneyPlateformVendor));
                total.put("returnPlateformVendor",returnPlateformVendor.add(total_returnPlateformVendor));
                total.put("returnOldVendor",returnOldVendor.add(total_returnOldVendor));
                total.put("customerNo",length);

            }else{
                total.put("inquiryGoodCount",total_inquiryGoodCount);
                total.put("quotationOldVendor",total_quotationOldVendor);
                total.put("quotationPlateformVendor",total_quotationPlateformVendor);
                total.put("unQuotation",total_unQuotation);
                total.put("dingbiaoOldVendor",total_dingbiaoOldVendor);
                total.put("dingbiaoPlateformVendor",total_dingbiaoPlateformVendor);
                total.put("orderGoodOldVendor",total_orderGoodOldVendor);
                total.put("orderGoodPlateformVendor",total_orderGoodPlateformVendor);
                total.put("orderNum",total_orderNum);
                total.put("orderMoneyOldVendor",total_orderMoneyOldVendor);
                total.put("orderMoneyPlateformVendor",total_orderMoneyPlateformVendor);
                total.put("returnPlateformVendor",total_returnPlateformVendor);
                total.put("returnOldVendor",total_returnOldVendor);
                total.put("customerNo",length);
            }
            totals.add(total);
        }
    }


    private void addIntoTotalItem(Map<String, Object> userItem, List<Map<String, Object>> totals,
                                  List<Map<String, Object>> list,
                                  CustomerStatisticsDto good, String type,Integer customerNo) {
        String userId = (String) userItem.get("user_id");
        totals.forEach(total->{
            String saleUserId = (String) total.get("saleUserId");
            if (saleUserId.equals(userId) && StringUtils.equals(type, (String) total.get("type"))){
                total.put("type", type);
                total.put("saleUserId", userId);
                total.put("saleUserName", userItem.get("userName"));
                if (list != null && list.size() > 0) {
                    boolean flag = false;
                    Map<String, Object> param = new HashMap<>();

                    for (Map<String, Object> service : list) {
                        String orgName = (String) service.get("name");
                        String orgNameInfo = (String) userItem.get("name");
                        if (StringUtils.equals(orgNameInfo, orgName)) {
                            flag = true;
                            param = service;
                            break;
                        }
                    }
                    String timeZone = "";
                    if (StringUtils.equals("type", "first")) {
                        timeZone = good.getStartTime() + "至" + good.getEndTime();
                    } else {
                        timeZone = good.getSecondStartTime() + "至" + good.getSecondEndTime();
                    }
                    param.put("timeZone", timeZone);

                    Integer total_inquiryGoodCount = (Integer) total.get("inquiryGoodCount") == null ? 0 : (Integer) total.get("inquiryGoodCount");
                    Integer total_quotationOldVendor = (Integer) total.get("quotationOldVendor") == null ? 0 : (Integer) total.get("quotationOldVendor");
                    Integer total_quotationPlateformVendor = (Integer) total.get("quotationPlateformVendor") == null ? 0 : (Integer) total.get("quotationPlateformVendor");
                    Integer total_unQuotation = (Integer) total.get("unQuotation") == null ? 0 : (Integer) total.get("unQuotation");
                    Integer total_dingbiaoOldVendor = (Integer) total.get("dingbiaoOldVendor") == null ? 0 : (Integer) total.get("dingbiaoOldVendor");
                    Integer total_dingbiaoPlateformVendor = (Integer) total.get("dingbiaoPlateformVendor") == null ? 0 : (Integer) total.get("dingbiaoOldVendor");
                    Integer total_orderGoodOldVendor = (Integer) total.get("orderGoodOldVendor") == null ? 0 : (Integer) total.get("orderGoodOldVendor");
                    Integer total_orderGoodPlateformVendor = (Integer) total.get("orderGoodPlateformVendor") == null ? 0 : (Integer) total.get("orderGoodPlateformVendor");
                    Integer total_orderNum = (Integer) total.get("orderNum") == null ? 0 : (Integer) total.get("orderNum");
                    BigDecimal total_orderMoneyOldVendor = (BigDecimal) total.get("orderMoneyOldVendor") == null ? new BigDecimal(0) : (BigDecimal) total.get("orderMoneyOldVendor");
                    BigDecimal total_orderMoneyPlateformVendor = (BigDecimal) total.get("orderMoneyPlateformVendor") == null ? new BigDecimal(0) : (BigDecimal) total.get("orderMoneyPlateformVendor");
                    BigDecimal total_returnPlateformVendor = (BigDecimal) total.get("returnPlateformVendor") == null ? new BigDecimal(0) : (BigDecimal) total.get("returnPlateformVendor");
                    BigDecimal total_returnOldVendor = (BigDecimal) total.get("returnOldVendor") == null ? new BigDecimal(0) : (BigDecimal) total.get("returnOldVendor");

                    if (flag) {
                        Integer inquiryGoodCount = (Integer) param.get("inquiryGoodCount") == null ? 0 : (Integer) param.get("inquiryGoodCount");
                        Integer quotationOldVendor = (Integer) param.get("quotationOldVendor") == null ? 0 : (Integer) param.get("quotationOldVendor");
                        Integer quotationPlateformVendor = (Integer) param.get("quotationPlateformVendor") == null ? 0 : (Integer) param.get("quotationPlateformVendor");
                        Integer unQuotation = (Integer) param.get("unQuotation") == null ? 0 : (Integer) param.get("unQuotation");
                        Integer dingbiaoOldVendor = (Integer) param.get("dingbiaoOldVendor") == null ? 0 : (Integer) param.get("dingbiaoOldVendor");
                        Integer dingbiaoPlateformVendor = (Integer) param.get("dingbiaoPlateformVendor") == null ? 0 : (Integer) param.get("dingbiaoOldVendor");
                        Integer orderGoodOldVendor = (Integer) param.get("orderGoodOldVendor") == null ? 0 : (Integer) param.get("orderGoodOldVendor");
                        Integer orderGoodPlateformVendor = (Integer) param.get("orderGoodPlateformVendor") == null ? 0 : (Integer) param.get("orderGoodPlateformVendor");
                        Integer orderNum = (Integer) param.get("orderNum") == null ? 0 : (Integer) param.get("orderNum");
                        BigDecimal orderMoneyOldVendor = (BigDecimal) param.get("orderMoneyOldVendor") == null ? new BigDecimal(0) : (BigDecimal) param.get("orderMoneyOldVendor");
                        BigDecimal orderMoneyPlateformVendor = (BigDecimal) param.get("orderMoneyPlateformVendor") == null ? new BigDecimal(0) : (BigDecimal) param.get("orderMoneyPlateformVendor");
                        BigDecimal returnPlateformVendor = (BigDecimal) param.get("returnPlateformVendor") == null ? new BigDecimal(0) : (BigDecimal) param.get("returnPlateformVendor");
                        BigDecimal returnOldVendor = (BigDecimal) param.get("returnOldVendor") == null ? new BigDecimal(0) : (BigDecimal) param.get("returnOldVendor");

                        total.put("inquiryGoodCount", inquiryGoodCount + total_inquiryGoodCount);
                        total.put("quotationOldVendor", quotationOldVendor + total_quotationOldVendor);
                        total.put("quotationPlateformVendor", quotationPlateformVendor + total_quotationPlateformVendor);
                        total.put("unQuotation", unQuotation + total_unQuotation);
                        total.put("dingbiaoOldVendor", dingbiaoOldVendor + total_dingbiaoOldVendor);
                        total.put("dingbiaoPlateformVendor", dingbiaoPlateformVendor + total_dingbiaoPlateformVendor);
                        total.put("orderGoodOldVendor", orderGoodOldVendor + total_orderGoodOldVendor);
                        total.put("orderGoodPlateformVendor", orderGoodPlateformVendor + total_orderGoodPlateformVendor);
                        total.put("orderNum", orderNum + total_orderNum);
                        total.put("orderMoneyOldVendor", orderMoneyOldVendor.add(total_orderMoneyOldVendor));
                        total.put("orderMoneyPlateformVendor", orderMoneyPlateformVendor.add(total_orderMoneyPlateformVendor));
                        total.put("returnPlateformVendor", returnPlateformVendor.add(total_returnPlateformVendor));
                        total.put("returnOldVendor", returnOldVendor.add(total_returnOldVendor));
                        total.put("customerNo", customerNo);


                    } else {
                        total.put("inquiryGoodCount", total_inquiryGoodCount);
                        total.put("quotationOldVendor", total_quotationOldVendor);
                        total.put("quotationPlateformVendor", total_quotationPlateformVendor);
                        total.put("unQuotation", total_unQuotation);
                        total.put("dingbiaoOldVendor", total_dingbiaoOldVendor);
                        total.put("dingbiaoPlateformVendor", total_dingbiaoPlateformVendor);
                        total.put("orderGoodOldVendor", total_orderGoodOldVendor);
                        total.put("orderGoodPlateformVendor", total_orderGoodPlateformVendor);
                        total.put("orderNum", total_orderNum);
                        total.put("orderMoneyOldVendor", total_orderMoneyOldVendor);
                        total.put("orderMoneyPlateformVendor", total_orderMoneyPlateformVendor);
                        total.put("returnPlateformVendor", total_returnPlateformVendor);
                        total.put("returnOldVendor", total_returnOldVendor);
                        total.put("customerNo", customerNo);
                        totals.add(total);
                    }
                }
            }
        });
    }


    private void addIntoTotalItem(Map<String, Object> item, List<SaleStatisticsDto> totals, String userId,String type) {

        
        
    }

    /**
     *
     * @param userId 销售员id
     * @param totals 总集合
     * @param type 类型 属于哪一段时间区间
     * @return
     */
    private boolean isAlreadyContains(String userId, List<SaleStatisticsDto> totals, String type) {
        boolean flag = false;
        for (int i = 0; i < totals.size(); i++) {
            String saleUserId = totals.get(i).getSaleUserId();
            String type1 = totals.get(i).getType();
            if (StringUtils.equals(userId,saleUserId) && StringUtils.equals(type1,type) ){
                flag = true;
                break;

            }
        }
        return flag;
    }


}
